<template>
  <div class="box">
    <template v-if="options.length">
      <ul class="select-ul" :style="ulStyle">
        <li v-for="(item,index) in options" :key="item[keyField] || index" :class="opClass(index)" @click="liClick(item,index)">{{ displayFun(item) }}</li>
      </ul>
    </template>
    <div v-else class="no-data" :style="ulStyle">{{ noDataText }}</div>
  </div>
</template>

<script>
export default {
  name: "SelectLi",
  props: {
    api: {
      type: [Function, Array],
      default: () => {},
      require: true
    },
    // 参数
    parameter: {
      type: Object,
      default: () => {}
    },
    // 显示的字段
    displayFun: {
      type: Function,
      default: () => {},
      require: true
    },
    // key 绑定的字段
    keyField: {
      type: String,
      default: "value"
    },
    noDataText: {
      type: String,
      default: "暂无数据"
    },
    ulStyle: {
      type: Object,
      default: () => {
        return {
          width: "160px"
        };
      }
    }
  },
  data() {
    return {
      options: [],
      activateKey: -1
    };
  },
  watch: {
    parameter: {
      handler() {
        this.init();
      },
      deep: true
    }
  },
  mounted() {
    this.init();
    this.$emit("init", this.init);
  },
  methods: {
    async init() {
      this.activateKey = -1;
      if (typeof this.api === "function") {
        this.options = await this.api(this.parameter);
      } else {
        this.options = this.api;
      }
    },
    opClass(index) {
      return index === this.activateKey ? "li-active" : "";
    },
    liClick(item, index) {
      this.activateKey = index;
      this.$emit("li-click", item);
    }
  }
};
</script>
<style scoped lang="scss" src="./index.scss"></style>
